package cn.algorithms_4ed.base.dataStructure;

/**
 * 定容 栈
 * <p/>
 * User: erhu
 * Date: 13-6-11
 * Time: 下午9:55
 */
public class FixedCapacityStack<T> {

    private T[] data;
    private int size;

    public FixedCapacityStack(int size) {
        data = (T[]) new Object[size];
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public void push(T t) {
        if (size == data.length) {
            resize(size << 1);
        }
        data[size++] = t;
    }

    public T pop() {
        T item = data[--size];
        data[size] = null;

        if (size > 0 && size == data.length / 4) {
            resize(size >> 1);
        }
        return item;
    }

    private void resize(int max) {
        T[] tmp = (T[]) new Object[max];
        System.arraycopy(data, 0, tmp, 0, size);
        /*for (int i = 0; i < size; i++) {
            tmp[i] = data[i];
        }*/
        data = tmp;
    }

}
